package com.lipiao.traveltreasure.controller.restaurant;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.lipiao.traveltreasure.bean.restaurantBean.*;
import com.lipiao.traveltreasure.bean.restaurantBean.weixin.MyTemplate;
import com.lipiao.traveltreasure.bean.restaurantBean.weixin.TemplateData;
import com.lipiao.traveltreasure.bean.restaurantBean.weixin.WxMssVo;
import com.lipiao.traveltreasure.dao.restaurant.OpenIdMapper;
import com.lipiao.traveltreasure.dao.restaurant.ShoppingCartMapper;
import com.lipiao.traveltreasure.service.restaurant.CommonService;
import com.lipiao.traveltreasure.service.restaurant.ShoppingCartService;
import com.lipiao.traveltreasure.service.restaurant.UserService;
import com.lipiao.traveltreasure.util.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 餐厅顾客 控制器
 * 1.添加购物车
 * 2.上传用户信息 用户id，用户名，用户头像
 */
@Api(tags = "点餐小程序-餐厅顾客")
@Controller
@RequestMapping(value = "/restaurantApi/user")
public class UserController {
    static String fileLocation = "/restaurantRes/";//图片资源访问路径
    //存储预返回页面的结果对象
    private Map<String, Object> result = new HashMap<>();
    //注入业务对象
    @Resource
    private UserService userService;
    //注入业务对象
    @Resource
    private CommonService commonService;
    @Resource
    private ShoppingCartService shoppingCartService;

//    @Resource
//    OpenIdMapper openIdMapper;


    /**
     * @param id          用户id
     * @param name        用户名
     * @param pictureFile 用户头像
     * @param request
     * @return
     */
    @ApiOperation(value = "添加用户信息", notes = "注意事项：POST请求，参数String id用户ID必填,String name用户名若没有可空, Part pictureFile用户头像若没有可空")
    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(String id, String name, Part pictureFile,
                                       HttpServletRequest request) {
        result = new HashMap<>();
        //获取提交文件名称
        String filename = pictureFile.getSubmittedFileName();//System.out.println("filename文件名"+filename);
        if (filename.equals("")) {
            System.out.println("filename文件 为空");
            userService.addUser(new User(id, name, ""));
            result.put("Result", "添加用户信息成功");
        } else {
            String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
            String filePath = request.getScheme() + "://" + request.getServerName() + fileLocation + filename;
            String pictureFileURL = filePath;//根路径+文件名
            //写入文件
            try {
                pictureFile.write(filename);
                userService.addUser(new User(id, name, pictureFileURL));
                result.put("Result", "添加用户信息成功");
            } catch (IOException e) {
                e.printStackTrace();
                result.put("Result", "添加用户信息失败");
            }
        }
        return result;
    }

    @ApiOperation(value = "查询所有用户信息", notes = "注意事项：GET请求，无参数")
    @GetMapping("/queryAllUser")
    @ResponseBody
    public Map<String, Object> queryAllUser() {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            List<User> userList = userService.queryAllUser();
            result.put("Result", "查询所有用户信息成功");
            result.put("UserList", userList);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("Result", "查询所有用户信息失败");
            result.put("UserList", "");
        }
        return result;
    }

    //oTIF45PvH31fu8m4VlExPgC31pJ0
    //code 测试0a1TCQYe20Rg4F01L20f2855Ze2TCQYi
    //post localhost:8080/restaurantApi/user/uploadAppInformation
    @ApiOperation(value = "上传小程序信息", notes = "注意事项：POST请求，参数String code")
    @PostMapping("/uploadAppInformation")
    @ResponseBody
    public Map<String, Object> uploadAppInformation(String code) {
        //防止返回信息重复
        result = new HashMap<>();
        System.out.println();
        //        //请求微信String appid,String secret,String code
        ////返回的参数unionid作为用户唯一标识
        String wxresult = "";//微信返回的字符串
        String appid = "wx2d3d4b6c0a11a93d";
        String secret = "e6980d562de6e120c7108316fa0e18a5";
        OpenIdJson openIdJson;
        try {
//            result = HttpUtil.doGet(
//                    "https://api.weixin.qq.com/sns/jscode2session?appid="
//                            + this.appID + "&secret="
//                            + this.appSecret + "&js_code="
//                            + code
//                            + "&grant_type=authorization_code", null);

            wxresult = HttpUtil.doPost(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + appid + "&secret="
                            + secret + "&js_code="
                            + code + "&grant_type=authorization_code", null);
            ObjectMapper mapper = new ObjectMapper();
            openIdJson = mapper.readValue(wxresult, OpenIdJson.class);
            System.out.println("wxresult"+wxresult);//输出请求结果
            System.out.println("getOpenid"+openIdJson.getOpenid());

            //openIdMapper.insert(openIdJson);//插入openIdJson数据
            //处理返回结果
            //防止返回信息重复
            result = new HashMap<>();
            result.put("session_key", openIdJson.getSession_key());
            result.put("openid", openIdJson.getOpenid());
        } catch (Exception e) {
            result.put("message","code参数 非法或已过期！"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    //localhost:8080/restaurantApi/user/uploadOrder
    @ApiOperation(value = "上传订单信息", notes = "注意事项：POST请求，JSON参数示例：{\n" +
            "\t\"openid\":\"dqidubqiudqiudg\",\n" +
            "    \"prices\":333.9,\n" +
            "\t\"foodlist\":[\n" +
            "\t\t{\n" +
            "\t\t\t\"foodid\":\"1\",\n" +
            "\t\t\t\"name\":\"可乐排骨\",\n" +
            "\t\t\t\"number\":1\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"foodid\":\"12\",\n" +
            "\t\t\t\"name\":\"糖醋萝卜\",\n" +
            "\t\t\t\"number\":1\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"foodid\":\"14\",\n" +
            "\t\t\t\"name\":\"雪碧\",\n" +
            "            \"number\":2\n" +
            "\t\t}\n" +
            "\t]\t\n" +
            "} ")
    @PostMapping("/uploadOrder")
    @ResponseBody
    public Map<String, Object> order(@RequestBody OrderJson orderJson) {
        result = new HashMap<>();
        //数据校验
        if (null == orderJson) {
            result.put("Result", "提交订单失败！空订单");
            return result;
        }
        if (null == orderJson.getOpenid() || orderJson.getOpenid().equals("")) {
            result.put("Result", "提交订单失败！openid为空");
            return result;
        }
        if (null == orderJson.getPrices() || orderJson.getPrices().equals(0.0)) {
            result.put("Result", "提交订单失败！总价格为空或0");
            return result;
        }
        if (null == orderJson.getFoodlist() || orderJson.getFoodlist().size() <= 0) {
            result.put("Result", "提交订单失败！没有添加菜品");
            return result;
        }
        if (orderJson.getFoodlist().contains(null) || orderJson.getFoodlist().contains("")) {
            result.put("Result", "提交订单失败！菜品信息包含空值或空字符串");
            return result;
        }
        for (int i = 0; i < orderJson.getFoodlist().size(); i++) {
            if (orderJson.getFoodlist().get(i).getFoodid() == null || orderJson.getFoodlist().get(i).getFoodid().equals("")) {
                result.put("Result", "提交订单失败！菜品信息包含0或空值或空字符串");
                return result;
            }
            if (orderJson.getFoodlist().get(i).getName() == null || orderJson.getFoodlist().get(i).getName().equals("")) {
                result.put("Result", "提交订单失败！菜品信息包含0或空值或空字符串");
                return result;
            }
            if (orderJson.getFoodlist().get(i).getNumber() == null || orderJson.getFoodlist().get(i).getNumber() == 0) {
                result.put("Result", "提交订单失败！菜品信息包含0或空值或空字符串");
                return result;
            }
        }
        //业务逻辑处理

        String openid = orderJson.getOpenid();//用户openid
        double prices = orderJson.getPrices();//订单总价格
        List<OrderJson.FoodlistBean> foodlist = orderJson.getFoodlist();//订单中的菜品列表

        for (int i = 0; i < foodlist.size(); i++) {
            //根据提交的id 查询完整菜品信息
            Food food = commonService.queryFoodById(foodlist.get(i).getFoodid());//根据id查菜
            String id = UUID.randomUUID() + "";//唯一标识符，单挑菜单记录
            //生成单挑购物车记录
            ShoppingCart shoppingCart = new ShoppingCart(id, openid, food.getId(), foodlist.get(i).getNumber(), food.getPrices());
            //保存单挑购物车记录
            shoppingCartService.save(shoppingCart);
        }
        // System.currentTimeMillis()
//UUID.randomUUID().toString().substring(0,10)  非纯数字 不能作为微信规定的订单号
        //发送订阅消息
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   //获取时间
        System.out.println(df.format(System.currentTimeMillis()));
        String date = df.format(System.currentTimeMillis());
        MyTemplate myTemplate = new MyTemplate("锐婷餐馆", System.currentTimeMillis()+"", prices + "", date);
        System.out.println(myTemplate);
        String pushResult = push(openid, myTemplate);

        JSONObject object = JSON.parseObject(pushResult);
        String errmsg = object.getString("errmsg");
        //         openIdMapper.selectOne(openid)
        result.put("orderResult", "提交订单成功！");
        result.put("pushResult", errmsg);

        return result;
    }

    //教程 https://www.jianshu.com/p/34c8c719db4c
    //这个access_token，是存在有效期的
    // 把access_token存到数据库，或者存到本地缓存，并且还要记录当前时间如果超过2个小时的话，就要重新获取了
    @GetMapping("/getAccessToken")
    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wx2d3d4b6c0a11a93d");
        params.put("APPSECRET", "e6980d562de6e120c7108316fa0e18a5");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String access_token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("access_token" + access_token);
        System.out.println("有效时长expires_in" + expires_in);
        return access_token;
    }


    /*
     * 发送订阅消息
     * */
//    @GetMapping("/pushOneUser")
//    public String pushOneUser() {
//        return push("o3DoL0WEdzcJ20AVJg1crP96gbjM",);
//    }

    public String push(String openid, MyTemplate myTemplate) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id("KI-Ia-44gWacp8aYNSthFAEMVjuqHP7SmxMRj4pVxWQ");//订阅消息模板id
        wxMssVo.setPage("pages/index/index");

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("thing1", new TemplateData(myTemplate.getStoreName()));//门店名称
        m.put("number2", new TemplateData(myTemplate.getId()));//订单编号
        m.put("amount3", new TemplateData(myTemplate.getOrderPrices()));//订单金额
        m.put("time5", new TemplateData(myTemplate.getOrderTime()));//订单时间
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }

}
